package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.GeneraLifeObser;
import com.ruihang.generalibrary.utils.GroupOrderHelper;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.beans.FProgram;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.adapter.RadioLookBackAdapter;
import com.sctvcloud.zhaohua_sd.ui.dialog.TimePopupDialog;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 广播（回看）
 */
public class RadioLockBackFragment extends ColumnBaseFragment implements RadioLookBackAdapter.ChoiceDateCallBack
        , TimePopupDialog.PopItemClick, CanRefreshLayout.OnRefreshListener
        , ExpandableListView.OnGroupClickListener, ExpandableListView.OnChildClickListener, CanRefreshLayout.IScrollView {
    @BindView(R.id.program_back_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.program_back_list)
    protected ExpandableListView proBack_list;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout scrollLay;
    private RadioLookBackAdapter lookbackAdapter;
    private TimePopupDialog timePopupDialog;
    public static final String TIME_TAG = "dia_time_choice";
    private List<FProgram> mList;
    // private boolean mIsLoading = false;
    // private boolean isFirtShowing = true;

    private String questUrl;
    private GroupOrderHelper groupOrderHelper;
    private String programUrl;
    private String pageUrl;
    private int dateCurrentPos;
    private boolean isRequesting = false;
    private TvFragment parentFragment;
    private FProgram choosedFProgram;

    public RadioLockBackFragment() {
    }

    public void setParentFragment(TvFragment parentFragment) {
        this.parentFragment = parentFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_radio_look_back, container, false);
        ButterKnife.bind(this, view);
        groupOrderHelper = new GroupOrderHelper();
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        proBack_list.setGroupIndicator(null);
        proBack_list.setOnGroupClickListener(this);
        proBack_list.setOnChildClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        scrollLay.setiScrollView(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (null == mList || mList.size() == 0) {
            refreshLayout.autoRefresh();
        }

    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (null == mList || mList.size() == 0) {
            refreshLayout.autoRefresh();
        }
        if (null != parentFragment && null != choosedFProgram) {
            parentFragment.setLookBackPlayMedia(choosedFProgram,true);
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onResume() {
        super.onResume();
        GeneraLifeObser.changeLifeState(this, GeneraLifeObser.STATE_RESUME);
    }

    @Override
    public void onDestroyView() {
        if (scrollLay != null) {
            scrollLay.setiScrollView(null);
        }
        if (proBack_list != null) {
            proBack_list.setOnChildClickListener(null);
            proBack_list.setOnGroupClickListener(null);
        }
        if (refreshLayout != null) {
            refreshLayout.setOnRefreshListener(null);
        }
        super.onDestroyView();
    }

    @Override
    public boolean canScrollUp(MotionEvent e) {
        return ViewCompat.canScrollVertically(proBack_list, -1);
    }

    @Override
    public boolean canScrollDown(MotionEvent e) {
        return ViewCompat.canScrollVertically(proBack_list, 1);
    }


    @Override
    public void getDateCallBack(int position, String url) {
        if (!TextUtils.isEmpty(url) && url.length() - 24 > 0) {
            pageUrl = url.substring(0, url.length() - 24);
            dateCurrentPos = position;
            if (timePopupDialog == null) {
                timePopupDialog = new TimePopupDialog().setPopItemClick(this);
            }
            timePopupDialog.show(getActivity().getSupportFragmentManager(), TIME_TAG);
        } else {
            toast("暂无数据");
        }
    }

    @Override
    public void getItemClick(int groupPosition, int childPosition) {
        FProgram fProgram = (FProgram) lookbackAdapter.getChild(groupPosition, childPosition);
        if (fProgram != null) {
            choosedFProgram = fProgram;
            if (null != parentFragment) {
                parentFragment.setLookBackPlayMedia(fProgram,true);
            }
            lookbackAdapter.setSelectedChildPos(childPosition);
            lookbackAdapter.setSelectedParentPos(groupPosition);
            lookbackAdapter.notifyDataSetChanged();
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "频道"));
            pairs.add(new Pair<>("位置", "新闻回放"));
            pairs.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(RadioLockBackFragment.this, "", fProgram.getProgrammeName(), "", 200, pairs);

        }

        //   toast("点击回看" + fProgram.getProgrammeTitle());
    }

    private RadioLookBackAdapter.ContentHolder selectedHolder;


    @Override
    public void selectTime(String year, String month, String day) {
        //toast(time);
        if (month.length() == 1) {
            month = "0" + month;
        }
        if (day.length() == 1) {
            day = "0" + day;
        }
        String dateStr = year + month + day;
        int dateInt = Integer.parseInt(dateStr);
        if (dateInt < 20180331) {
            programUrl = pageUrl + year + month + day + ".json";
        } else {
            programUrl = pageUrl + year + "/" + month + "/" + day + "/" + year + month + day + ".json";
        }
        //programUrl = "/sctv/lookback/2/20170715.json";
        getProList(programUrl, dateCurrentPos);

    }

    @Override
    public void onRefresh() {
//        if (mIsLoading || isFirtShowing) {
//            if(refreshLayout.isRefreshing()){
//                refreshLayout.refreshComplete();
//            }
//            return;
//        }
        // mIsLoading = true;
//        if (((TvFragment) getParentFragment()).getProgramBackUrl() == null) {
//            ((TvFragment) getParentFragment()).requestProgramBackUrl();
//            return;
//        }
        getFirstList();
    }

    /**
     * 请求频道回看新闻数据
     */
    public void getFirstList() {
//        if (isRequesting) {
//            return;
//        }
        isRequesting = true;
        NetUtils.getNetAdapter().getProgramArray(getOwnerName(), questUrl, new AbsListNetCallback<FProgram>
                (ListTypeUtils.FProgram()) {

            @Override
            public void onSuc(List<FProgram> firstList) {
                if (firstList == null || firstList.size() == 0 || TextUtils.isEmpty(firstList.get(0).getProgrammeUrl())) {
                    onError(null, null);
                    return;
                }
                mList = new ArrayList<>();
                mList.addAll(firstList);
                getSecondList();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                isRequesting = false;
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private void getSecondList() {
        for (int i = 0; i < mList.size(); i++) {
            groupOrderHelper.addOne();
            String url = mList.get(i).getProgrammeUrl();
            getProList(url, i);
        }
    }

    private void getProList(final String programmeUrl, final int i) {
        isRequesting = true;
        NetUtils.getNetAdapter().getProgramArray(getOwnerName(), programmeUrl, new AbsListNetCallback<FProgram>(ListTypeUtils.FProgram()) {
            @Override
            public void onSuc(List<FProgram> list) {
                initData(list, getInt1());
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                initData(null, getInt1());
                // toast(R.string.look_back_no_data);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                isRequesting = false;
                onNetFinish();
            }
        }.setInt1(i));
    }


    private synchronized void onNetFinish() {
        if (null != groupOrderHelper && groupOrderHelper.getCount() == 0) {
            //mIsLoading = false;
            refreshLayout.refreshComplete();
        }
    }

    private void initData(List<FProgram> list, int index) {
        if (ListUtils.isListValued(list)) {
            mList.get(index).setProgrammeList(list);
        } else {
            mList.get(index).setProgrammeList(null);
        }
        if (!groupOrderHelper.removeOne()) {
            return;
        }
        if (lookbackAdapter == null) {
            lookbackAdapter = new RadioLookBackAdapter(mList, getActivity()).setChoiceDateCallBack(this);
            proBack_list.setAdapter(lookbackAdapter);
            if (mList.size() > 1) {
                proBack_list.expandGroup(0);
            }
        } else {
            lookbackAdapter.setData(mList);
//            if (mList.size() > 1) {
//                proBack_list.expandGroup(0);
//            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //  if (!mIsLoading) {
            Fragment bf = parentFragment;
            if (parentFragment == null
                    || TextUtils.isEmpty((parentFragment).getProgramBackUrl())) {
                //toast(R.string.loading_no_data);
                onNetFinish();
            } else {
                getFirstList();
            }
            //}
            //isFirtShowing = false;
        }
    }

//    public void setIsLoading(boolean isLoading) {
//        mIsLoading = isLoading;
//    }

    public void setProgramUrl(String programUrl) {
        this.programUrl = programUrl;
    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition, long id) {
//        if (ListUtils.isListValued(mList.get(groupPosition).getProgrammeList())) {
//            return false;
//        }
        return false;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        for (int i = 0; i < mList.size(); i++) {
            List<FProgram> list = mList.get(i).getProgrammeList();
            if (!ListUtils.isListValued(list)) {
                continue;
            }
            for (int j = 0; j < list.size(); j++) {
                if (i == groupPosition && j == childPosition) {
                    list.get(j).setSelect(true);
                } else {
                    list.get(j).setSelect(false);
                }
            }
        }
        lookbackAdapter.notifyDataSetChanged();
        getItemClick(groupPosition, childPosition);
        return true;
    }

    public void setQuestUrl(String questUrl) {
        this.questUrl = questUrl;
    }

}
